package _0725_Split_Linked_List_in_Parts;

/**
 * Date: 2021/9/22 9:20
 * Content:
 * 执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
 * 内存消耗：38.5 MB, 在所有 Java 提交中击败了63.90%的用户
 */
public class Solution {

    public ListNode[] splitListToParts(ListNode head, int k) {
        int n = 0;
        for (ListNode p = head; p != null; p = p.next) n++;

        ListNode[] res = new ListNode[k];
        ListNode p = head;
        for (int i = 0; i < k; i++) {
            int len = n / k;
            if (i + 1 <= n % k) len++;
            res[i] = p;
            for (int j = 0; j < len - 1; j++) p = p.next;
            if (p != null) {
                ListNode q = p.next;
                p.next = null;
                p = q;
            }
        }
        return res;
    }

    public static void main(String[] args) {

        ListNode head = (new MyLinkedList(new int[]{1, 2, 3})).getHead();
        ListNode[] res = (new Solution()).splitListToParts(head, 5);
        for (ListNode t : res) MyLinkedList.printLinkedList(t);
    }
}
